package com.xyy.config;

import com.xyy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT拦截器
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的Authorization
        String authHeader = request.getHeader("Authorization");
        String requestURI = request.getRequestURI();
        
        log.info("JWT拦截器处理请求: {} {}", request.getMethod(), requestURI);
        log.info("Authorization头: {}", authHeader);
        
        // 如果是OPTIONS请求，直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            log.info("OPTIONS请求，直接放行");
            return true;
        }
        
        // 检查是否需要token验证的路径
        if (isExcludedPath(requestURI, request)) {
            log.info("排除路径，不需要token验证: {}", requestURI);
            return true;
        }
        
        // 验证token
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
            log.warn("未提供有效的认证token: {}", requestURI);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":500,\"message\":\"未提供有效的认证token\",\"data\":null}");
            return false;
        }
        
        String token = authHeader.substring(7); // 去掉"Bearer "前缀
        
        try {
            // 验证token
            if (jwtUtil.isTokenExpired(token)) {
                log.warn("token已过期: {}", requestURI);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":500,\"message\":\"token已过期\",\"data\":null}");
                return false;
            }
            
            // 将用户信息存储到request中，供后续使用
            String username = jwtUtil.getUsernameFromToken(token);
            String tokenType = jwtUtil.getTypeFromToken(token);
            
            // 根据token类型设置不同的ID
            if ("admin".equals(tokenType)) {
                Long adminId = jwtUtil.getAdminIdFromToken(token);
                request.setAttribute("username", username);
                request.setAttribute("adminId", adminId);
                request.setAttribute("userId", adminId); // 为了兼容性，也设置userId
                log.info("管理员Token验证成功，设置adminId: {}, username: {}", adminId, username);
                
                if (adminId == null) {
                    log.warn("从管理员token中提取的adminId为null，token内容可能有问题");
                }
            } else {
                Long userId = jwtUtil.getUserIdFromToken(token);
                request.setAttribute("username", username);
                request.setAttribute("userId", userId);
                log.info("用户Token验证成功，设置userId: {}, username: {}", userId, username);
                
                if (userId == null) {
                    log.warn("从用户token中提取的userId为null，token内容可能有问题");
                }
            }
            return true;
        } catch (Exception e) {
            log.error("token验证失败: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":500,\"message\":\"token验证失败\",\"data\":null}");
            return false;
        }
    }
    
    /**
     * 判断是否为不需要token验证的路径
     */
    private boolean isExcludedPath(String requestURI, HttpServletRequest request) {
        String[] excludedPaths = {
            "/user/login",
            "/user/register", 
            "/user/sendEmailCode",
            "/user/resetPassword",
            "/user/forgotPassword",
            "/user/verifySecurityQuestions",
            "/user/getUserInfoForReset",
            "/user/validateEmail",
            "/user/validateUsername",
            "/user/validatePhone",
            "/user/validateEmailCode",
            "/user/validateCaptcha",
            "/user/getCaptcha",
            "/user/refreshToken"
        };
        
        for (String path : excludedPaths) {
            if (requestURI.equals(path)) {
                return true;
            }
        }
        
        // 活动相关的公开接口（不需要登录）
        String[] publicActivityPaths = {
            "/activity/list"
        };
        
        for (String path : publicActivityPaths) {
            if (requestURI.equals(path)) {
                return true;
            }
        }
        
        // 活动详情查询（不需要登录）
        if (requestURI.matches("/activity/\\d+") && request.getMethod().equals("GET")) {
            return true;
        }
        
        // 活动封面访问（不需要登录）
        if (requestURI.startsWith("/activity/cover/")) {
            return true;
        }
        
        // 检查报名状态（不需要登录）
        if (requestURI.equals("/activity-registration/check") && request.getMethod().equals("GET")) {
            return true;
        }
        
        return false;
    }
} 